package com.houdoudou.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import com.houdoudou.bean.Branch;
import com.houdoudou.bean.Sort;

public class BranchDao {

	 Connection conn=null;

	public BranchDao(Connection conn) {
		super();
		this.conn = conn;
	}
	 
	public  int create( List<Branch> branches ) throws SQLException{	
		int result=0;
		  PreparedStatement pstm=null; 
		   Statement  stm=null;
		   ResultSet rs=null; 	
		   String sql=null;
		   sql = "insert  into branch (id,product,name,volume,isAuth,price) "
       			+ "values (?,?,?,?,?,?)";
	        try {        	
	        	for(int i=0;i<branches.size();i++){	        		
	        	pstm=conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
	        	pstm.setInt(1, branches.get(i).getId());
	        	pstm.setInt(2, branches.get(i).getProduct());
	        	pstm.setString(3,branches.get(i).getName());    
	        	pstm.setInt(4, branches.get(i).getVolume());
	        	pstm.setInt(5, branches.get(i).getIsAuth());
	        	pstm.setDouble(6, branches.get(i).getPrice());
	        	
				pstm.executeUpdate();
	        	}			
		   		
			} finally{
				ConnFactory.closeStatment(pstm, pstm, rs);
			}			
		return result;
	}
	public  void delete(int product) throws SQLException{	
		
		  PreparedStatement pstm=null; 
		   Statement  stm=null;
		   ResultSet rs=null; 	
		   String sql=null;
	        try {
	        	sql = "delete  from branch where product="+product+"";		        	
				stm=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
				stm.executeUpdate(sql);
				
			} finally{
				ConnFactory.closeStatment(pstm, pstm, rs);
			}			
		
	}
	public List< Branch> search( String sql) throws SQLException{	
		List< Branch> branches= new ArrayList<Branch>();
		  PreparedStatement pstm=null; 
		   Statement  stm=null;
		   ResultSet rs=null; 	
	
	        try {
	        		        	
				stm=conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
				rs=stm.executeQuery(sql);
				while(rs.next()){
					Branch branch = new Branch();
					branch.setId(rs.getInt("id"));
					branch.setProduct(rs.getInt("product"));
					branch.setName(rs.getString("name"));
					branch.setVolume(rs.getInt("volume"));
					branch.setIsAuth(rs.getInt("isAuth"));
					branch.setPrice(rs.getDouble("price"));
					branches.add(branch);
				}
			} finally{
				ConnFactory.closeStatment(pstm, pstm, rs);
			}			
		return branches;
	}	
	 public static  String  getSearchSql(Branch branch){
			String sql="select * from branch where product = "+ branch.getProduct();				
			return sql;
		}	
}
